<?php
namespace app\admin\controller;

use think\Controller;
class Common extends Controller
{
    public function _initialize()
    {
        if (!session('?admin_auth')) {
            session('go', url('admin/index/index'));
            $this->redirect('admin/auth/login');
        }
        \think\Hook::add('app_end', 'app\\admin\\behavior\\Clearcache');
        \think\Hook::listen('admin_init');
        \think\Config::set('app_trace', false);
    }
    protected function modeldata($b = [])
    {
        $m = request();
        if (!$b) {
            $b = $m->param();
        }
        if (!isset($b['model'])) {
            $b['model'] = $m->controller();
        }
        if (!isset($b['where'])) {
            $b['where'] = [];
        } else {
            foreach ($b['where'] as &$p) {
                foreach ($p as &$tt) {
                    $tt = is_string($tt) ? trim($tt) : $tt;
                }
            }
        }
        if (!isset($b['with'])) {
            $b['with'] = '';
        }
        $uu = \think\Loader::model($b['model']);
        if (input('order/a')) {
            $uu->order(input('order/a'));
        }
        $vv = [];
        $ww = input('rows', 0, 'intval') ?: 1000;
        $vv = $uu::with($b['with'])->where($b['where'])->paginate($ww);
        $vv = $vv->toArray();
        $vv['rows'] = $vv['data'];
        unset($vv['data']);
        $this->success('获取成功！', '', $vv);
    }
    protected function fetchform($xx = array(), $yy = array())
    {
        $zz = $this->getform($xx, $yy);
        $this->assign($zz);
        $this->assign('_data', $xx);
        $this->success('', '', $this->fetch('admin@common/form'));
    }
    protected function getform($xx = array(), $yy = array())
    {
        $aaa = [];
        $yy['formname'] = isset($yy['formname']) ? $yy['formname'] : request()->module() . '_' . request()->controller() . '_' . request()->action();
        $yy['action'] = isset($yy['action']) ? $yy['action'] : request()->module() . '/' . request()->controller() . '/' . request()->action();
        $bbb = ['status' => array('eq', 1), 'name' => array('eq', $yy['formname'])];
        if ($zz = \think\Db::name('form')->where($bbb)->find()) {
            $bbb = ['status' => array('eq', 1), 'category_id' => array('eq', $zz['id'])];
            $ccc = \app\admin\model\Formfield::where($bbb)->field(true)->order('sort desc,id asc')->select();
            $ddd = [];
            foreach ($ccc as $eee => $fff) {
                $ggg = [];
                $ggg['id'] = $fff['id'];
                $ggg['config'] = $fff['config'];
                $ggg['title'] = $fff['title'];
                $ggg['remark'] = $fff['remark'];
                $ggg['type'] = substr($fff['type'], 5);
                if ($fff['subtable'] && $fff['extfield']) {
                    $ggg['field'] = $fff['subtable'] . '[' . $fff['extfield'] . ']' . '[' . $fff['name'] . ']';
                } elseif ($fff['extfield']) {
                    $ggg['field'] = $fff['extfield'] . '[' . $fff['name'] . ']';
                } elseif ($fff['subtable']) {
                    $ggg['field'] = $fff['subtable'] . '[' . $fff['name'] . ']';
                } else {
                    $ggg['field'] = $fff['name'];
                }
                switch ($fff['defaultvaluetype']) {
                    case '0':
                        $ggg['value'] = $fff['defaultvalue'];
                        break;
                    case '1':
                        $ggg['value'] = input($fff['defaultvalue']);
                        break;
                    case '2':
                        $ggg['value'] = config($fff['defaultvalue']);
                        break;
                    case '3':
                        if ($fff['subtable'] && $fff['extfield']) {
                            $hhh = $xx[$fff['subtable']][$fff['extfield']];
                        } elseif ($fff['extfield']) {
                            $hhh = $xx[$fff['extfield']];
                        } elseif ($fff['subtable']) {
                            $hhh = $xx[$fff['subtable']];
                        } else {
                            $hhh = $xx;
                        }
                        $ggg['value'] = $this->get_point_value($hhh, $fff['defaultvalue']);
                        break;
                    default:
                        $ggg['value'] = $fff['defaultvalue'];
                        break;
                }
                $ddd[$fff['group']][$fff['id']] = $ggg;
            }
            $zz['action'] = \think\Url::build($yy['action']);
            $zz['formtime'] = time();
            $aaa['_form'] = $zz;
            $aaa['_groups'] = $ddd;
            if (isset($yy['ext_id']) && $yy['ext_id']) {
                $bbb = array('category_id' => array('eq', $yy['ext_id']), 'status' => array('eq', 1));
                if ($iii = \app\admin\model\Extendfield::where($bbb)->field(true)->order('sort desc,id asc')->select()) {
                    $jjj = [];
                    foreach ($iii as $eee => $kkk) {
                        $ggg = [];
                        $ggg['id'] = $kkk['id'];
                        $ggg['config'] = $kkk['config'];
                        $ggg['title'] = $kkk['title'];
                        $ggg['remark'] = $kkk['remark'];
                        $ggg['type'] = substr($kkk['type'], 5);
                        if (isset($yy['ext_table']) && $yy['ext_table']) {
                            $ggg['field'] = $yy['ext_table'] . '[ext]' . '[' . $kkk['name'] . ']';
                        } else {
                            $ggg['field'] = 'ext[' . $kkk['name'] . ']';
                        }
                        $ggg['value'] = '';
                        if ($xx) {
                            if (isset($yy['ext_table']) && $yy['ext_table']) {
                                $hhh = $xx[$yy['ext_table']]['ext'];
                                $ggg['value'] = isset($hhh[$kkk['name']]) ? $hhh[$kkk['name']] : $kkk['value'];
                            } elseif (isset($xx['ext'])) {
                                $hhh = $xx['ext'];
                                $ggg['value'] = isset($hhh[$kkk['name']]) ? $hhh[$kkk['name']] : $kkk['value'];
                            }
                        }
                        $jjj[$kkk['group']][$kkk['id']] = $ggg;
                    }
                    $aaa['_extgroups'] = $jjj;
                }
            } elseif (isset($yy['single_ext_id']) && $yy['single_ext_id']) {
                $bbb = array('single_id' => array('eq', $yy['single_ext_id']), 'status' => array('eq', 1));
                if ($iii = \app\admin\model\Extendfield::where($bbb)->field(true)->order('sort desc,id asc')->select()) {
                    $jjj = [];
                    foreach ($iii as $eee => $kkk) {
                        $ggg = [];
                        $ggg['id'] = $kkk['id'];
                        $ggg['config'] = $kkk['config'];
                        $ggg['title'] = $kkk['title'];
                        $ggg['remark'] = $kkk['remark'];
                        $ggg['type'] = substr($kkk['type'], 5);
                        if (isset($yy['ext_table']) && $yy['ext_table']) {
                            $ggg['field'] = $yy['ext_table'] . '[ext]' . '[' . $kkk['name'] . ']';
                        } else {
                            $ggg['field'] = 'ext[' . $kkk['name'] . ']';
                        }
                        $ggg['value'] = '';
                        if ($xx) {
                            if (isset($yy['ext_table']) && $yy['ext_table']) {
                                $hhh = $xx[$yy['ext_table']]['ext'];
                                $ggg['value'] = isset($hhh[$kkk['name']]) ? $hhh[$kkk['name']] : $kkk['value'];
                            } elseif (isset($xx['ext'])) {
                                $hhh = $xx['ext'];
                                $ggg['value'] = isset($hhh[$kkk['name']]) ? $hhh[$kkk['name']] : $kkk['value'];
                            }
                        }
                        $jjj[$kkk['group']][$kkk['id']] = $ggg;
                    }
                    $aaa['_extgroups'] = $jjj;
                }
            }
            if (input('__modal') == 1) {
                $aaa['__modal'] = 1;
            } else {
                $aaa['__modal'] = 0;
            }
            $aaa['namespace'] = ns();
            return $aaa;
        } else {
            $this->error('表单配置错误！');
        }
    }
    protected function ebadd($yy = [], $lll = false)
    {
        if (request()->isGet()) {
            $this->fetchform();
        } else {
            if (request()->isPost()) {
                $yy['model'] = isset($yy['model']) ? $yy['model'] : get_model_controller(request()->controller());
                $yy['module'] = isset($yy['module']) ? $yy['module'] : request()->module();
                $uu = \think\Loader::model($yy['module'] . '/' . $yy['model']);
                $mmm = input();
                $yy['allowfield'] = isset($yy['allowfield']) ? $yy['allowfield'] : true;
                $yy['validate'] = isset($yy['validate_scene']) ? $yy['model'] . '.' . $yy['validate_scene'] : $yy['model'];
                if (false !== ($nnn = $uu->allowField($yy['allowfield'])->validate($yy['validate'])->save($mmm))) {
                    if (isset($yy['relation']) && $yy['relation']) {
                        foreach ($yy['relation'] as $ooo => $ppp) {
                            switch ($ppp['type']) {
                                case 'hasone':
                                    $uu->{$ooo}()->save($mmm[$ooo]);
                                    break;
                                case 'hasmany':
                                    $uu->{$ooo}()->saveAll($mmm[$ooo]);
                                    break;
                                case 'manytomany':
                                    $uu->{$ooo}()->saveAll($mmm[$ooo]);
                                    break;
                            }
                        }
                    }
                    if ($lll == true) {
                        return $nnn;
                    } else {
                        $this->success('新增成功！', '', ['id' => $nnn]);
                    }
                } else {
                    $this->error($uu->getError());
                }
            }
        }
    }
    protected function ebedit($yy = [], $lll = false)
    {
        if (request()->isGet()) {
            $nnn = isset($yy['id']) ? $yy['id'] : input('id');
            $yy['model'] = isset($yy['model']) ? $yy['model'] : get_model_controller(request()->controller());
            $yy['module'] = isset($yy['module']) ? $yy['module'] : request()->module();
            $uu = \think\Loader::model($yy['module'] . '/' . $yy['model']);
            $this->fetchform($uu->get($nnn));
        } else {
            if (request()->isPost()) {
                $nnn = isset($yy['id']) ? $yy['id'] : input('id');
                $yy['model'] = isset($yy['model']) ? $yy['model'] : get_model_controller(request()->controller());
                $yy['module'] = isset($yy['module']) ? $yy['module'] : request()->module();
                $uu = \think\Loader::model($yy['module'] . '/' . $yy['model']);
                $xx = $uu->get($nnn);
                $mmm = input();
                $yy['allowfield'] = isset($yy['allowfield']) ? $yy['allowfield'] : true;
                $yy['validate'] = isset($yy['validate_scene']) ? $yy['model'] . '.' . $yy['validate_scene'] : $yy['model'];
                if (false !== $uu->allowField($yy['allowfield'])->validate($yy['validate'])->save($mmm, ['id' => $nnn])) {
                    if (isset($yy['relation']) && $yy['relation']) {
                        foreach ($yy['relation'] as $ooo => $ppp) {
                            switch ($ppp['type']) {
                                case 'hasone':
                                    $ppp['validate'] = isset($ppp['validate_scene']) ? $ooo . '.' . $ppp['validate_scene'] : $ooo;
                                    $ppp['allowfield'] = isset($ppp['allowfield']) ? $ppp['allowfield'] : true;
                                    if (false === $uu->{$ooo}->allowField($ppp['allowfield'])->validate($ppp['validate'])->save($mmm[$ooo])) {
                                        $this->error($uu->{$ooo}->getError());
                                    }
                                    break;
                                case 'hasmany':
                                    $uu->{$ooo}()->delete();
                                    $uu->{$ooo}()->saveAll($mmm[$ooo]);
                                    break;
                                case 'manytomany':
                                    $uu->{$ooo}()->detach(true);
                                    $uu->{$ooo}()->saveAll($mmm[$ooo]);
                                    break;
                            }
                        }
                    }
                    if ($lll == true) {
                        return true;
                    } else {
                        return $this->success('修改成功！');
                    }
                } else {
                    $this->error($uu->getError());
                }
            }
        }
    }
    protected function ebdelete($yy = [], $xx = [])
    {
        if (false !== ($aaa = $this->_ebdelete($yy, $xx))) {
            $this->success('删除成功！', '', $aaa);
        } else {
            $this->error('删除失败！');
        }
    }
    protected function _ebdelete($yy = [], $xx = [])
    {
        if (isset($xx['ids'])) {
            $qqq = (array) $xx['ids'];
        } elseif ($qqq = input('ids')) {
            $qqq = explode(',', $qqq);
        }
        if ($qqq) {
            $yy['model'] = isset($yy['model']) ? $yy['model'] : get_model_controller(request()->controller());
            $yy['module'] = isset($yy['module']) ? $yy['module'] : request()->module();
            $uu = \think\Loader::model($yy['module'] . '/' . $yy['model']);
            $rrr['id'] = array('in', $qqq);
            if (isset($yy['relation']) && $yy['relation']) {
                $sss = $uu->where($rrr)->select();
                if ($sss) {
                    foreach ($sss as $ttt) {
                        foreach ($yy['relation'] as $ooo => $ppp) {
                            switch ($ppp['type']) {
                                case 'hasone':
                                    if (isset($ppp['sub'])) {
                                        $this->_ebdelete($ppp['sub'], ['ids' => $ttt['id']]);
                                    }
                                    $ttt->{$ooo}->delete();
                                    break;
                                case 'hasmany':
                                    if (isset($ppp['sub'])) {
                                        $uuu = $ttt->{$ooo};
                                        $vvv = [];
                                        foreach ($uuu as $www) {
                                            $vvv[] = $www['id'];
                                        }
                                        if ($vvv) {
                                            $this->_ebdelete($ppp['sub'], ['ids' => $vvv]);
                                        }
                                    }
                                    $ttt->{$ooo}()->delete();
                                    break;
                                case 'manytomany':
                                    $ttt->{$ooo}()->detach(true);
                                    break;
                            }
                        }
                        $ttt->delete();
                    }
                }
            } else {
                $sss = $uu->where($rrr)->select();
                $uu->where($rrr)->delete();
            }
            $aaa = [];
            foreach ($sss as $xxx) {
                $aaa[] = $xxx->toArray();
            }
            return $aaa;
        } else {
            return false;
        }
    }
    protected function ebstatus($yy = [])
    {
        if (isset($yy['ids'])) {
            $qqq = (array) $yy['ids'];
        } elseif ($qqq = input('ids')) {
            $qqq = explode(',', $qqq);
        }
        if (empty($qqq)) {
            $this->error('请选择要 操作 的数据！');
        }
        if (isset($yy['value'])) {
            $fff = (int) $yy['value'];
        } else {
            $fff = input('value', 0, 'intval') ? 1 : 0;
        }
        $this->ebfield($qqq, 'status', $fff, $yy);
    }
    protected function ebsort($yy = [])
    {
        if (isset($yy['ids'])) {
            $qqq = (array) $yy['ids'];
        } elseif ($qqq = input('ids')) {
            $qqq = explode(',', $qqq);
        }
        if (empty($qqq)) {
            $this->error('请选择要 操作 的数据！');
        }
        if (isset($yy['value'])) {
            $fff = (int) $yy['value'];
        } else {
            $fff = input('value', 0, 'intval');
        }
        $this->ebfield($qqq, 'sort', $fff, $yy);
    }
    protected function ebfield($qqq, $yyy, $fff, $yy = [])
    {
        $yy['model'] = isset($yy['model']) ? $yy['model'] : get_model_controller(request()->controller());
        $yy['module'] = isset($yy['module']) ? $yy['module'] : request()->module();
        $uu = \think\Loader::model($yy['module'] . '/' . $yy['model']);
        $zzz = [];
        $zzz['id'] = array('in', $qqq);
        $aaaa = $uu->where($zzz)->setField($yyy, $fff);
        if (false === $aaaa) {
            $this->error('操作失败！');
        } elseif (is_numeric($aaaa)) {
            $this->success('操作成功！');
        }
    }
    private function get_point_value($xx = [], $bbbb)
    {
        $cccc = strpos($bbbb, '.');
        if (false === $cccc) {
            return isset($xx[$bbbb]) ? $xx[$bbbb] : false;
        } else {
            $eee = mb_substr($bbbb, 0, $cccc);
            if (isset($xx[$eee])) {
                return $this->get_point_value($xx[$eee], mb_substr($bbbb, $cccc + 1));
            } else {
                return false;
            }
        }
    }
    public function _empty()
    {
        $dddd = request()->action();
        switch ($dddd) {
            case 'add':
                if (request()->isGet()) {
                    $this->fetchform();
                } elseif (request()->isPost()) {
                    $this->ebadd();
                }
                break;
            case 'edit':
                if (request()->isGet()) {
                    $xx = \think\Db::name(request()->controller())->find(input('id'));
                    $this->fetchform($xx);
                } elseif (request()->isPost()) {
                    $this->ebedit();
                }
                break;
            case 'resort':
                if (request()->isGet()) {
                } elseif (request()->isPost()) {
                    $this->ebsort();
                }
                break;
            case 'delete':
                $this->ebdelete();
                break;
            case 'status':
                $this->ebstatus();
                break;
            default:
                $this->error('错误请求！');
                break;
        }
    }
}